<?php
class Controller_BoFaculty extends Controller_Boprepare
{
    /**
     * 系别信息(Create, Read)
     */
    public function actionAddMajor()
    {
        $Pnew_major = isset($_POST['new_major']) ? $_POST['new_major'] : NULL;

        if($Pnew_major && Major::find('major = ?', $Pnew_major)->query()->major_id == '')
        {
            $newMajorRecord = new Major(
                array(
                    'haschild'  => 0,
                    'major'     => $Pnew_major,
                    'parent_id' => 0,
            ));
            $newMajorRecord->save();
        }
    }
    /**
     * 系别信息(Update, Read)
     */
    public function actionEditMajor()
    {
        $Pmajor_id = isset($_POST['major_id']) ? $_POST['major_id'] : NULL;
        $Pmajor = isset($_POST['major']) ? $_POST['major'] : NULL;

        if($Pmajor_id && $Pmajor)
        {
            $major = Major::find('major_id = ?', $Pmajor_id)->query();
            $major->major = $Pmajor;
            $major->save();

            return $this->_forward('bofaculty/addmajor');
        }
    }
    /**
     * 系别信息(Delete)
     */
    public function actionDeleteMajor()
    {
        $Gmajor_id = isset($_GET['major_id']) ? $_GET['major_id'] : NULL;

        if($Gmajor_id && Teacher::find('major_id = ?', $Gmajor_id)->query()->teacher_id == '')
        {
            Major::meta()->deleteWhere('major_id = ?', $Gmajor_id);
        }

        return $this->_forward('bofaculty/addmajor');
    }

    /**
     * 头衔信息(Create, Read)
     */
    public function actionAddTitle()
    {
        $Pnew_title = isset($_POST['new_title']) ? $_POST['new_title'] : NULL;

        if($Pnew_title && Title::find('title = ?', $Pnew_title)->query()->title_id == '')
        {
            $newTitleRecord = new Title(
                array(
                    'haschild'  => 0,
                    'title'     => $Pnew_title,
                    'parent_id' => 0,
            ));
            $newTitleRecord->save();
        }
    }
    /**
     * 头衔信息(Update, Read)
     */
    public function actionEditTitle()
    {
        $Ptitle_id = isset($_POST['title_id']) ? $_POST['title_id'] : NULL;
        $Ptitle    = isset($_POST['title'])    ? $_POST['title']    : NULL;

        if($Ptitle_id && $Ptitle)
        {
            $title = Title::find('title_id = ?', $Ptitle_id)->query();
            $title->title = $Ptitle;
            $title->save();

            return $this->_forward('bofaculty/addtitle');
        }
    }
    /**
     * 头衔信息(Delete)
     */
    public function actionDeleteTitle()
    {
        $Gtitle_id = isset($_GET['title_id']) ? $_GET['title_id'] : NULL;

        if($Gtitle_id && TeacherTitle::find('title_id = ?', $Gtitle_id)->query()->teacher_id == '')
        {
            Title::meta()->deleteWhere('title_id = ?', $Gtitle_id);
        }

        return $this->_forward('bofaculty/addtitle');
    }

    /**
     * 课程信息(Create)
     */
    public function actionAddCourse()
    {
        $Pnew_course = isset($_POST['new_course']) ? $_POST['new_course'] : NULL;

        if($Pnew_course && Course::find('course = ?', $Pnew_course)->query()->course_id == '')
        {
            $newCourseRecord = new Course(
                array(
                    'course' => $Pnew_course,
            ));
            $newCourseRecord->save();
        }
    }
    /**
     * 课程信息(Update)
     */
    public function actionEditCourse()
    {
        $Pcourse_id = isset($_POST['course_id']) ? $_POST['course_id'] : NULL;
        $Pcourse    = isset($_POST['course'])    ? $_POST['course']    : NULL;

        if($Pcourse_id && $Pcourse)
        {
            $course = Course::find('course_id = ?', $Pcourse_id)->query();
            $course->course = $Pcourse;
            $course->save();

            return $this->_forward('bofaculty/addcourse');
        }
    }
    /**
     * 课程信息(Delete)
     */
    public function actionDeleteCourse()
    {
        $Gcourse_id = isset($_GET['course_id']) ? $_GET['course_id'] : NULL;

        // 还要删除这门课的所有附件
        if($Gcourse_id && TeacherCourse::find('course_id = ?', $Gcourse_id)->query()->course_id == '')
        {
            Course::meta()->deleteWhere('course_id = ?', $Gcourse_id);
        }

        return $this->_forward('bofaculty/addcourse');
    }

    /**
     * 教师-课程信息(Create, Read, Update, Delete)
     */
    public function actionEditTCMap()
    {
        $tid = $_SESSION['tid'];
        $Pcourse = isset($_POST['course']) ? $_POST['course'] : NULL;

        if($Pcourse)
        {
            // 更新关系表时 先删除全部 teacher_id = tid 的值，然后再输入新值
            TeacherCourse::meta()->deleteWhere('teacher_id = ?', $tid);

            foreach($Pcourse as $course_id)
            {
                $obj = new TeacherCourse(
                    array(
                        'teacher_id' => $_SESSION['tid'],
                        'course_id'  => $course_id,
                ));
                //$obj->save(NULL, 'create');
                $obj->save();
            }
        }

        $ycourses = Course::find()
            ->join('teacher_course', '', 'course.course_id = teacher_course.course_id')
            ->where('teacher_course.teacher_id = ?', $_SESSION['tid'])
            ->distinct()->all()->query();
      if(!$ycourses->isEmpty())
      {
         $ncourses = Course::find('course_id not in (?)', $ycourses->values('course_id'))
            ->all()->query();
      }
      else
      {
         $ncourses = Course::find()->all()->query();
      }

        $this->_view['ycourses'] = $ycourses;
        $this->_view['ncourses'] = $ncourses;

        $this->_view['cssfile']  = 'bofaculty.css';
    }

    /**
     * 课件信息(Create)
     */
    public function actionAddTDoc()
    {
        $ycourses = Course::find()
            ->join('teacher_course', '', 'course.course_id = teacher_course.course_id')
            ->where('teacher_course.teacher_id = ?', $_SESSION['tid'])
            ->distinct()->all()->query();

        $Pteacher_id = isset($_POST['teacher_id']) ? $_POST['teacher_id'] : NULL;
        $Pcourse_id  = isset($_POST['course_id'])  ? $_POST['course_id']  : NULL;
        $Ftdoc       = isset($_FILES['tdoc'])      ? $_FILES['tdoc']      : NULL;

        $notice = '请上传文件';
        if($Pteacher_id && $Pcourse_id && $Ftdoc)
        {
            // 此为表逻辑操作，应当被封装为如下语句
            //$notice = $this->_tdocs->uploadTdocs($Pteacher_id, $Pcourse_id);

            /**
             * 定义允许上传的文件类型
             * 可在数据库修改
             * 'jpg,png,gif, doc,docx,ppt,pptx,xsl,xslx, txt,pdf, rar,zip,tgz'
             */
            $allowExts = Q::ini('appini/uploadAllowExts');

            /**
             * NOTICE : 该值与PHP设置 {php.ini} 有关
             * 定义允许上传的最大尺寸
             * 可在数据库修改
             * 10 * 1024 * 1024 (10M)
             */
            $maxSize   = Q::ini('appini/uploadMaxSize');

            /**
             * 定义允许 课件文件夹
             * '../upload_tdoc'
             */
            $tdocDir   = Q::ini('appini/tdocDir');

            $uploader  = new Helper_Uploader();
            $tdoc      = $uploader->file('tdoc');

            $tdocid    = md5($_SERVER['REQUEST_TIME'] . $tdoc->filename());
            $filename  = urlencode($tdocid . '.' . strtolower($tdoc->extname()));
            $tdoc->move($tdocDir."/{$filename}");

            $newTdocRecord = new Tdoc(
                array(
                    'teacher_id' => $Pteacher_id,
                    'course_id'  => $Pcourse_id,
                    'filename'   => $tdoc->filename(),
                    'path'       => $tdocDir."/{$filename}",
                    'created'    => $_SERVER['REQUEST_TIME'],
                    'size'       => round($tdoc->filesize() / 1024 / 1024 , 2).'M',
            ));
            $newTdocRecord->save();

            $notice = '文件'.$tdoc->filename().'上传成功！';
        } // 上传完毕

        $this->_view['ycourses'] = $ycourses;
        $this->_view['notice']     = $notice;
    }
    /**
     * 课件信息(Read)
     */
    public function actionListTdoc()
    {
        switch($_SESSION['lrole_id'])
        {
            // 管理员
            case 1:
            case 6:
                $tdocs = Tdoc::find()
                    ->join('teachers', '', 'teachers.teacher_id = tdocs.teacher_id')
                    ->join('courses' , '', 'courses.course_id   = tdocs.course_id')
                    ->all()->query();
                break;
            // 老师
            case 4:
                $tdocs = Tdoc::find()
                    ->join('teacher', '', 'teacher.teacher_id = tdoc.teacher_id')
                    ->join('course' , 'course', 'course.course_id   = tdoc.course_id')
                    ->where('teacher.teacher_id = ?', $_SESSION['tid'])
                    ->all()->query();
                break;
        }

        $this->_view['tdocs']   = $tdocs;
        $this->_view['cssfile'] = 'bofaculty.css';
    }
    /**
     * 课件信息(Update)
     */
    public function actionEditTdoc()
    {
        $Ptdoc_id   = isset($_POST['tdoc_id'])   ? $_POST['tdoc_id']   : NULL;
        $Pcourse_id = isset($_POST['course_id']) ? $_POST['course_id'] : NULL;

        if($Ptdoc_id && $Pcourse_id)
        {
            $tdoc = Tdoc::find('tdoc_id = ?', $Ptdoc_id)->query();
            $tdoc->course_id = $Pcourse_id;
            $tdoc->save();

            return $this->_forward('bofaculty/listtdoc');
        }

        $ycourses = Course::find()
            ->join('teacher_course', '', 'course.course_id = teacher_course.course_id')
            ->where('teacher_course.teacher_id = ?', $_SESSION['tid'])
            ->distinct()->all()->query();

        $this->_view['ycourses'] = $ycourses;
    }
    /**
     * 课件信息(Delete)
     */
    public function actionDeleteTdoc()
    {
        $Gtdoc_id = isset($_GET['tdoc_id']) ? $_GET['tdoc_id'] : NULL;
        $tdoc = Tdoc::find('tdoc_id = ?', $Gtdoc_id)->query();

        if($Gtdoc_id && $tdoc->tdoc_id != '')
        {
            unlink($tdoc->filepath);
            $tdoc->destroy();
        }

        return $this->_forward('bofaculty/listtdoc');
    }

    /**
     * 教师信息(Create)
     * beta
     */
    public function actionAddTeacher()
    {
        $Pname         = isset($_POST['tname'])         ? $_POST['tname']        : NULL;
        $Pmajor_id     = isset($_POST['tmajor_id'])     ? $_POST['tmajor_id']    : NULL;
        $Ptitle        = isset($_POST['ttitle'])        ? $_POST['ttitle']       : NULL;
        $Pemail        = isset($_POST['temail'])        ? $_POST['temail']       : NULL;
        $Pphone        = isset($_POST['tphone'])        ? $_POST['tphone']       : NULL;
        $Pfax          = isset($_POST['tfax'])          ? $_POST['tfax']         : NULL;
        $Paccesscode   = isset($_POST['taccesscode'])   ? $_POST['taccesscode']  : NULL;
        $Pdescription  = isset($_POST['tdescription'])  ? $_POST['tdescription'] : NULL;
        $Pshowresearch = isset($_POST['tshowresearch']) ? 1 : 0;
        $Pprofile_path = 'misc/t_profiles/t_profile_'.md5($Pname).'.jpg';       // 不支持中文，必须 urlencode()
        $Pstatus       = 1;
        $uploader      = new Helper_Uploader();

        if($Pname && $Pmajor_id && $Ptitle && !$uploader->allfiles()->isEmpty())
        {
         if(strpos($Pdescription , '<div>') !== FALSE)
         {
            $Pdescription  = str_replace('<div>', '<p>', $Pdescription );
         }
         if(strpos($Pdescription , '</div>') !== FALSE)
         {
            $Pdescription  = str_replace('</div>', '</p>', $Pdescription );
         }
         if(strpos($Pdescription , '<br />') !== FALSE)
         {
            $Pdescription  = str_replace('<br />', '</p><p>', $Pdescription );
         }
            $newTeachersRecord = new Teacher(
                array(
                    'name'         => $Pname,
                    'major_id'     => $Pmajor_id,
                    'email'        => $Pemail,
                    'phone'        => $Pphone,
                    'fax'          => $Pfax,
                    'description'  => $Pdescription,
                    'accesscode'   => $Paccesscode,
                    'profile_path' => $Pprofile_path,
                    'showresearch' => $Pshowresearch,
                    'status'       => $Pstatus,
            ));


            if(Teacher::find('name = ?', $Pname)->query()->teacher_id == '')
            {
                // 执行操作：保存新教师信息
                $newTeachersRecord->save();

                // 执行操作：保存新教师头像
                $uploader->file('tprofile')->move($Pprofile_path);

                // 执行操作：保存新老师登录帐号
                $newTeacherId = Teacher::find('profile_path = ?', $Pprofile_path)->query()->teacher_id;
                $newCibLoginRecord = new Login(
                    array(
                        'cib_usr'    => $Pname,
                        'cib_pwd'    => -9999999,
                        'teacher_id' => $newTeacherId,
                        'role_id'    => 4,

                ));
                $newCibLoginRecord->save();

                // 执行操作：保存新老师-头衔对应关系
                foreach($Ptitle as $title_id)
                {
                    $obj = new TeacherTitle(
                        array(
                            'teacher_id' => $newTeacherId,
                            'title_id'   => $title_id,
                    ));
                    //$obj->save(NULL, 'create');
                    $obj->save();
                }
            }

            $this->_viewname = 'welcome';
        }
    }
    /**
     * 教师信息(Read)
     */
    public function actionListTeacher()
    {
    }
    /**
     * 教师信息(Update)
     */
    public function actionEditTeacher()
    {
        $tid = $_SESSION['tid'];
        $Pmajor_id     = isset($_POST['tmajor_id'])     ? $_POST['tmajor_id']    : NULL;
        $Ptitle        = isset($_POST['ttitle'])        ? $_POST['ttitle']       : NULL;
        $Pemail        = isset($_POST['temail'])        ? $_POST['temail']       : NULL;
        $Pphone        = isset($_POST['tphone'])        ? $_POST['tphone']       : NULL;
        $Pfax          = isset($_POST['tfax'])          ? $_POST['tfax']         : NULL;
        $Paccesscode   = isset($_POST['taccesscode'])   ? $_POST['taccesscode']  : NULL;
        $Pdescription  = isset($_POST['tdescription'])  ? $_POST['tdescription'] : NULL;
        $Pshowresearch = isset($_POST['tshowresearch']) ? 1 : 0;

        // 执行操作：更改头像
        $uploader = new Helper_Uploader();
        if(!$uploader->allfiles()->isEmpty())                                              // 表示有头像上传
        {
            unlink($dest = Teacher::find('teacher_id = ?', $tid)->query()->profile_path); // 删除旧头像
            $uploader->file('tprofile')->move($dest);                                      // 添加新头像
        }

        if($Pmajor_id && $Ptitle)
        {
         if(strpos($Pdescription , '<div>') !== FALSE)
         {
            $Pdescription  = str_replace('<div>', '<p>', $Pdescription );
         }
         if(strpos($Pdescription , '</div>') !== FALSE)
         {
            $Pdescription  = str_replace('</div>', '</p>', $Pdescription );
         }
         if(strpos($Pdescription , '<br />') !== FALSE)
         {
            $Pdescription  = str_replace('<br />', '</p><p>', $Pdescription );
         }
            // 执行操作：更新教师信息
            $teacher = Teacher::find('teacher_id = ?', $_SESSION['tid'])->query();
            $teacher->email        = $Pemail;
            $teacher->phone        = $Pphone;
            $teacher->fax          = $Pfax;
            $teacher->major_id     = $Pmajor_id;
            $teacher->accesscode   = $Paccesscode;
            $teacher->description  = $Pdescription;
            $teacher->showresearch = $Pshowresearch;

            $teacher->save();

            // 执行操作：更新老师与头衔对应表
            TeacherTitle::meta()->deleteWhere('teacher_id = ?', $_SESSION['tid']);
            foreach($Ptitle as $title_id)
            {
                $obj = new TeacherTitle(
                    array(
                        'teacher_id' => $_SESSION['tid'],
                        'title_id'   => $title_id,
                ));
                //$obj->save(NULL, 'create');
                $obj->save();
            }

         $this->_viewname = 'welcome';
        }

        // 尚未提交数据，准备数据
        if(empty($POST))
        {
            $ytitles = Title::find()
                ->join('teacher_title', '', 'title.title_id = teacher_title.title_id')
                ->where('teacher_id = ?', $_SESSION['tid'])
                ->distinct()->all()->query();

            $ntitles = Title::find('title_id not in (?)', $ytitles->values('title_id'))
                ->all()->query();

            $this->_view['ytitles'] = $ytitles;
            $this->_view['ntitles'] = $ntitles;
            $this->_view['cssfile'] = 'bofaculty.css';
        }
    }
    /**
     * 教师信息(Update)
     */
    public function actionDeleteTeacher()
    {
        $Gteacher_id = isset($_GET['teacher_id']) && is_numeric($_GET['teacher_id']) ? $_GET['teacher_id'] : NULL;

        if($Gteacher_id)
        {
            $teacher = Teacher::find('teacher_id = ?', $Gteacher_id)->query();
            $teacher->status = 'out';
            $teacher->save();
        }

        return $this->_forward('bofaculty/listteacher');
    }
    /**
     * 教师信息(Update)
     */
    public function actionRetriveTeacher()
    {
        $Gteacher_id = isset($_GET['teacher_id']) && is_numeric($_GET['teacher_id']) ? $_GET['teacher_id'] : NULL;

        if($Gteacher_id)
        {
            $teacher = Teacher::find('teacher_id = ?', $Gteacher_id)->query();
            $teacher->status = 'in';
            $teacher->save();
        }

        return $this->_forward('bofaculty/listteacher');
    }
}